﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using Lilium.UI.Controls;
using Lilium.UI.Layout;
using System.Windows.Forms;
using Microsoft.WindowsCE.Forms;
using System.Drawing;

namespace Lilium.UI.Forms
{
    public sealed class FormViewport : IViewport<System.Windows.Forms.Control>
    {
        private const int SIPBarHeight = 26;

        public FormViewport(Form form)
        {
            if (form == null) throw new ArgumentNullException("form");

            m_ControlFactory = new ControlFactory();
            m_Form = form;
            m_InputPanel = new InputPanel();
            m_LayoutPanel = new Panel()
            {
                AutoScroll = true,
                Size = GetViewportSize(),
            };
            m_Layout = new LayoutAdapter(LayoutPanel);
            m_InputPanel.EnabledChanged += (object sender, EventArgs e) =>
            {
                LayoutPanel.Size = GetViewportSize();
            };
            m_Form.Controls.Add(m_LayoutPanel);
        }

        #region IViewport<Control> Members

        public TResult RunUI<TResult>(UIMonad<TResult> ui)
        {
            if (ui == null) throw new ArgumentNullException("uiMonad");

            var state = new UIState<System.Windows.Forms.Control>(ControlFactory, Layout);
            var result = ui.RunUIFunc(state);
            return result;
        }

        #endregion

        private Size GetViewportSize()
        {
            var viewportSize = InputPanel.VisibleDesktop.Size;
            if (!InputPanel.Enabled)
                viewportSize.Height -= SIPBarHeight;
            return viewportSize;
        }

        #region private IControlFactory<System.Windows.Forms.Control> ControlFactory

        private readonly IControlFactory<System.Windows.Forms.Control> m_ControlFactory;

        private IControlFactory<System.Windows.Forms.Control> ControlFactory { get { return m_ControlFactory; } }

        #endregion

        #region public Form Form

        private readonly Form m_Form;

        public Form Form { get { return m_Form; } }

        #endregion

        #region private InputPanel InputPanel

        private readonly InputPanel m_InputPanel;

        private InputPanel InputPanel { get { return m_InputPanel; } }

        #endregion

        #region private ILayout<System.Windows.Forms.Control> Layout

        private readonly ILayout<System.Windows.Forms.Control> m_Layout;

        private ILayout<System.Windows.Forms.Control> Layout { get { return m_Layout; } }

        #endregion

        #region private Panel LayoutPanel

        private readonly Panel m_LayoutPanel;

        private Panel LayoutPanel { get { return m_LayoutPanel; } }

        #endregion
    }
}